﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ProgNetComponents.Data.SqlCe;
using System.Data.SqlServerCe;
using ProgNetComponentsDx.Options;
using ProgNetComponents.Classes;

namespace Wydatki
{
    public static class AppUpdate
    {
        static SqlCeDataManager helper = new SqlCeDataManager();

        public static void Update(int fromAction)
        {
            List<Action> actions = new List<Action>();
            bool executed = false;
            #region add actions
            actions.Add(new Action(CreateApp));
            actions.Add(new Action(Update1));
            actions.Add(new Action(Update2));
            actions.Add(UpdateRokPodatkowy);
            #endregion

            if (fromAction == 0)
            {
                CreateApp();
                SetOpt("DB_UPDATE", actions.Count); 
            }
            else
            {
                #region execute actions
                for (int i = fromAction; i < actions.Count; i++)
                {
                    executed = true;
                    try
                    {
                        actions[i].Invoke();
                    }
                    catch (Exception ex)
                    {
                        ex.Log("Błąd wykonania akcji " + i);
                    }

                }
                if (executed)
                {
                    SetOpt("DB_UPDATE", actions.Count);
                }
                #endregion
            }
        }
        private static void SetOpt(object optionId, object val)
        {
            NamedObject name = new NamedObject("@NAZWA", OptionCache.GetKey(optionId));
            NamedObject value = new NamedObject("@WARTOSC", val.AsString());

            int o = helper.ExecuteScalar("SELECT COUNT(1) FROM STP_OPCJE WHERE STP_OP_NAZWA = @NAZWA", name).AsInt();
            if (o == 0)
            {
                helper.ExecuteNonQuery("INSERT INTO STP_OPCJE(STP_OP_NAZWA, STP_OP_WARTOSC) VALUES (@NAZWA, @WARTOSC)", name, value);
            }
            else
            {
                helper.ExecuteNonQuery("UPDATE STP_OPCJE SET STP_OP_WARTOSC = @WARTOSC WHERE STP_OP_NAZWA = @NAZWA", name, value);
            }
        }
        private static void CreateApp()
        {
            SqlCeEngine eng = new SqlCeEngine(SqlCeDataManager.GlobalConnectionString);
            eng.CreateDatabase();
            ExecuteQieries(Properties.Resources.SqlScripts, "CreateApp");
            ExecuteQieries(Properties.Resources.InsertGrupyKPiR, "CreateApp - InsertGrupyKPiR");
            ExecuteQieries(Properties.Resources.InsertGrupyVatS, "CreateApp - InsertGrupyVatS");
            ExecuteQieries(Properties.Resources.InsertGrupyVatZ, "CreateApp - InsertGrupyVatZ");
            ExecuteQieries(Properties.Resources.InsertLotto, "CreateApp - InsertLotto");
            ExecuteQieries(Properties.Resources.InsertOpcje, "CreateApp - InsertOpcje");
        }
        private static void Update1()
        {
            ExecuteQieries(Properties.Resources.Update1, "Update 1");
        }

        private static void Update2()
        {
            ExecuteQieries(Properties.Resources.Update2, "Update 2");
        }
        private static void UpdateRokPodatkowy()
        {
            object o = helper.ExecuteScalar("SELECT MAX(STP_LP_ROK) FROM STP_LATA_PODATKOWE");
            if (o != null)
                SetOpt(Init.InitFormOptionNames.Global.RokPodatkowy, o.AsInt(DateTime.Now.Year));
        }
        private static void ExecuteQieries(string queries, string name)
        {
            string[] str = queries.XSplit(@"\s+GO;\s+", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline);
            for (int i=0; i < str.Length; i++)
            {
                try
                {
                    if (str[i].Trim().IsNotNull())
                    {
                        helper.ExecuteNonQuery(str[i]);
                        if (helper.LastException != null)
                            LogException(name, str[i], i, helper.LastException);
                    }
                }
                catch (Exception ex)
                {
                    LogException(name, str[i], i, ex);
                }
            }
        }
        private static void LogException(string name, string query, int no, Exception ex)
        {
            string str = "-------------------------------------------" + Constants.NewLineLinux +
            ("Błąd w skrypcie: " + name + ", polecenie numer: " + no) + Constants.NewLineLinux +
            ("Skrypt: " + query) + Constants.NewLineLinux +
            "-------------------------------------------";
            ex.LogError(str);
        }
    }

}
